package com.firewolf.hibernate.relationship.many_many.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.relationship.many_many.dto.Category;
import com.firewolf.hibernate.relationship.many_many.dto.Item;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;
	
	@Test
	public void saveCustomer(){
		openSession();
		
		Item item1 = new Item();
		item1.setItemName("Item1");
		Item item2 = new Item();
		item1.setItemName("Item2");
		
		Category category = new Category();
		category.setCategoryName("Category1");
		category.getItems().add(item1);
		category.getItems().add(item2);
		
		session.save(item1);
		session.save(item2);
		session.save(category);
		
		closeSession();
	}
	
	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}
	
	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("many2many.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
